#include "Calc.h"

int Calc::docalc(){
	int op = getOperatorTop();	

	if(op ==')') {
		popOperator2();
		int r=0;
		do {
			r=docalc();
		} while( r!='(');
		return 0;
	}
	if(op=='(') {
		popOperator2();
		return op;
	}
	int num1 = popNumber2();
	int num2 = popNumber2();

	op = popOperator2();
	if(op =='+'){
		pushNumber2(num2+num1);
	}
	else if(op=='-'){
		pushNumber2(num2-num1);
	}
	else if(op=='*'){
		pushNumber2(num2*num1);
	}
	else if(op=='/'){

	}

	return op;
}
void Calc::pushNumber2(int v){
	if (ptrVS==0){
		ptrVS = &valuestack[0];
		*ptrVS = v;
	}
	else if(ptrVS <&valuestack[63]){
		ptrVS++;
		*ptrVS = v;

	}
	else{
		//cout << "number stack is full\n";
		//error
		ptrVS--;
	}
}
int Calc::popNumber2() {
	int value;
	if(ptrVS>=&valuestack[0]){
		value = *ptrVS;
		*ptrVS = 0;
		ptrVS--;
		return value;
	}
	else{
		//error
	}
	
}
void Calc::pushOperator2(int op){
	if(ptrOS ==0){
		ptrOS = &operatorstack[0];
		*ptrOS = op;
	}
	else if(ptrOS < &operatorstack[63]){
		ptrOS++;
		*ptrOS = op;
	}
	else{
		//cout <<"operator stack is full\n";
		//error
	}
}
int Calc::popOperator2(){
	int value;
	if(ptrOS >=&operatorstack[0]){
		value = *ptrOS;
		*ptrOS = 0;
		ptrOS--;
		return value;
	}
	else{
		return 0;
		//cout << "operator stack is empty\n";
		//error
	}
}
int Calc::isOperatorStackEmpty2(){
	if (ptrOS==0) 
		return 1;
	return (ptrOS < &operatorstack[0]);
}
int Calc::isNumberStackEmpty(){
	return (ptrVS == &valuestack[0]);
}
int Calc::getNumberStackTop(){
	return *ptrVS;
}
int Calc::getOperatorTop(){
	return *ptrOS;
}
int Calc::getPrecedence(int token){
	switch (token){
	case '+':
	case '-':
		return 1;
		break;
	case '*':
	case '/':
		return 2;
		break;
	case '(':
	case ')':
		return 3;
		break;
	default:
		return 0;
	}
} 
bool Calc::isoperator(int token){
	if(token =='+' || token =='-' || token =='*' || token=='/')
		return true;
	else
		return false;
}
void Calc::checkingOP(int token){
	while( !isOperatorStackEmpty2() ){
				int op = getOperatorTop();
				
				if((getPrecedence(op) >=  getPrecedence(token))){
					if(op=='(') {
//						pushOperator(op);
						break;
					}

						docalc();

					

				}
				else
				{
					break;
				}
			}
}
//void Calc::pushOperator(int c){
//	if(opStack<opTop){
//		opStack++;
//		*opStack = c;		
//	}
//}